package yannan.voiplock4ble.task;

import android.util.Log;

import com.google.gson.Gson;
import com.yongchun.library.BuildConfig;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import yannan.voiplock4ble.base.MyApplication;
import yannan.voiplock4ble.bean.CommonResponse;
import yannan.voiplock4ble.bean.LockRecordBean;
import yannan.voiplock4ble.bean.LockRecordBeanDao;
import yannan.voiplock4ble.db.DaoUtils;
import yannan.voiplock4ble.db.daomanager.LockRecordDaoManager;
import yannan.voiplock4ble.net.NetUtils;
import yannan.voiplock4ble.net.base.NetworkCallBack;
import yannan.voiplock4ble.utils.TimeUtils;

/**
 * 说明：上传开锁记录子线程
 * 作者：mainTel
 * 时间：2016/11/23 10:14
 * 备注：
 */
public class UpOrDownLockRecordTask extends Thread {

    String lockserialId;
    String nowTime;

    public static UpOrDownLockRecordTask create(String lockserialId, String time) {
        UpOrDownLockRecordTask recordTask = new UpOrDownLockRecordTask();
        recordTask.lockserialId = lockserialId;
        recordTask.nowTime = time;
        return recordTask;
    }


    @Override
    public void run() {
//        upLoadOrDownLockRecord("Ade");
        if (MyApplication.getInterface().userBean != null) {
            NetUtils.getNetworkService().getNewestRecord(MyApplication.getInterface().userBean.userId,
                    lockserialId, "1").enqueue(new NetworkCallBack<CommonResponse>() {
                @Override
                public void onSuc(CommonResponse resBody) {
                    if (resBody.returnValue != null)
                        upLoadOrDownLockRecord(resBody.returnValue);
                    else {
                        if (nowTime.equals("0")) {
                            upLoadOrDownLockRecord("2100-01-01 00:00:00");
                        } else {
                            upLoadOrDownLockRecord("2016-01-01 00:00:00");
                        }
                    }
                }

                @Override
                public void onFail(String msg) {
                }
            });
        }
    }

    /**
     * 查询并上传数据
     *
     * @param time 服务器最新时间
     */
    private void upLoadOrDownLockRecord(String time) {
        if (TimeUtils.getStr2Long(time) > TimeUtils.getStr2Long(nowTime)) { //下载
            downloadLockRecord(time);
        } else { //上传
            upLoadLockRecord(time);
        }
    }

    /**
     * 全量更新
     * @param time
     */
    private void downloadLockRecord(String time) {
        EventBus.getDefault().postSticky("cancelRecordRefresh");
        if (MyApplication.getInterface().userBean != null)
            NetUtils.getNetworkService().getUnlockingRecord(
                    MyApplication.getInterface().userBean.userId,
                    "2016-01-01 00:00:00",
                    time,
                    "0",
                    "50",
                    lockserialId
            ).enqueue(new NetworkCallBack<List<LockRecordBean>>() {
                @Override
                public void onSuc(List<LockRecordBean> resBody) {
                    if (resBody != null && resBody.size() != 0) {
                        DaoUtils.getDao(LockRecordDaoManager.class).deleteAll();
                        DaoUtils.getDao(LockRecordDaoManager.class).insertOrReplaceList(resBody);
                        EventBus.getDefault().post("UpOrDownLockRecordTask_update");
                    }
                }

                @Override
                public void onFail(String msg) {
                     EventBus.getDefault().postSticky("cancelRecordRefresh");
                    if (com.yongchun.library.BuildConfig.DEBUG) Log.e("LockRecordFragment", "获取失败");
                }
            });
    }

    private void upLoadLockRecord(String time) {
        List<LockRecordBean> list = DaoUtils.getDao(LockRecordDaoManager.class).getQueryBuilder()
                .where(LockRecordBeanDao.Properties.LockserialId.eq(lockserialId)
                        , LockRecordBeanDao.Properties.UnlockingDate.gt(time))
                .orderDesc(LockRecordBeanDao.Properties.UnlockingDate)
                .list();
        if (list.size() == 0)
            return;
        Gson gson = new Gson();
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("[");
        int i = 0;
        for (LockRecordBean bean :
                list) {
            stringBuffer.append(gson.toJson(bean));
            i++;
            if (i < list.size()) {
                stringBuffer.append(",");
            }
        }
        stringBuffer.append("]");
        if (BuildConfig.DEBUG) Log.e("UpOrDownLockRecordTask", stringBuffer.toString());
        NetUtils.getNetworkService().uploadLockRecord(stringBuffer.toString())
                .enqueue(new NetworkCallBack<CommonResponse>() {
                    @Override
                    public void onSuc(CommonResponse resBody) {
                         EventBus.getDefault().postSticky("cancelRecordRefresh");
                        if (BuildConfig.DEBUG) Log.d("UpOrDownLockRecordTask", "上传成功");
                    }

                    @Override
                    public void onFail(String msg) {
                         EventBus.getDefault().postSticky("cancelRecordRefresh");
                        if (BuildConfig.DEBUG) Log.d("UpOrDownLockRecordTask", "上传失败");
                    }
                });
    }
}
